import router from './router'
import type { RouteRecordRaw } from 'vue-router'
import { isRelogin } from '@/config/axios/service'
import { getAccessToken } from '@/utils/auth'
import { useTitle } from '@/hooks/web/useTitle'
import { useNProgress } from '@/hooks/web/useNProgress'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { useDictStoreWithOut } from '@/store/modules/dict'
import { useUserStoreWithOut } from '@/store/modules/user'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { removeToken } from '@/utils/auth'

const { start, done } = useNProgress()

const { loadStart, loadDone } = usePageLoading()

const parseURL = (
  url: string | null | undefined
): { basePath: string; paramsObject: { [key: string]: string } } => {
  if (url == null) {
    return { basePath: '', paramsObject: {} }
  }

  const questionMarkIndex = url.indexOf('?')
  let basePath = url
  const paramsObject: { [key: string]: string } = {}

  if (questionMarkIndex !== -1) {
    basePath = url.substring(0, questionMarkIndex)
    const queryString = url.substring(questionMarkIndex + 1)
    const searchParams = new URLSearchParams(queryString)
    searchParams.forEach((value, key) => {
      paramsObject[key] = value
    })
  }

  return { basePath, paramsObject }
}

router.beforeEach(async (to, from, next) => {
  start()
  loadStart()

  // 移除登录验证，直接允许访问所有页面
  if (to.path === '/login') {
    next()
  } else {
    const userStore = useUserStoreWithOut()
    const hasToken = getAccessToken()

    // 如果没有token，说明用户未登录，直接允许访问
    if (!hasToken) {
      next()
      return
    }

    // isRelogin.show = true
    try {
      // 调用getPermissionInfo接口验证登录状态
      await userStore.setUserInfoAction()
      next()
    } catch (error) {
      console.error('登录状态验证失败，可能已过期', error)
      removeToken()
      // 如果接口调用失败，清除token并允许访问（保持当前的无登录限制逻辑）
      userStore.resetState()
      // next('/login')
    } finally {
      isRelogin.show = false
    }
  }
})

router.afterEach((to) => {
  useTitle(to?.meta?.title as string)
  done()
  loadDone()
})
